<script setup lang="ts">
import { computed, ref, reactive } from 'vue';
import { useVbenDrawer } from '@vben/common-ui';
import { cloneDeep } from '@vben/utils';
import {
  Form,
  FormItem,
  Input,
  Select,
  Table,
  Button,
  Popconfirm,
  message,
  Tag,
} from 'ant-design-vue';
import { useBeforeCloseDiff } from '#/utils/popup';
import {
  wxMsgTempAdd,
  wxMsgTempUpdate,
  wxMsgTempInfo,
} from '#/api/system/wxMsgTemp';
import type { WxMsgTempForm, Keyword } from '#/api/system/wxMsgTemp/model';
import { planContentOptions } from '@vben/constants';

const emit = defineEmits<{ reload: [] }>();

const isUpdate = ref(false);
const title = computed(() =>
  isUpdate.value ? '编辑微信模板' : '新增微信模板',
);

// --- 表单数据 ---
const getDefaultValues = (): Partial<WxMsgTempForm> => ({
  title: '',
  templateCode: undefined,
  templateId: '',
  status: '0',
  pagePath: '',
  remark: '',
  keywordsList: [],
});

const formData = ref<Partial<WxMsgTempForm>>(getDefaultValues());
const formRef = ref();

// --- 动态表格数据 ---
const editableKeywords = reactive<Record<string, Keyword>>({});

const keywordColumns = [
  { title: '关键词名称', dataIndex: 'name', width: '20%' },
  { title: '关键词ID', dataIndex: 'keywordId', width: '20%' },
  { title: '映射字段', dataIndex: 'mappingField', width: '23%' },
  { title: '默认值', dataIndex: 'defaultValue', width: '23%' },
  { title: '操作', dataIndex: 'operation', width: '14%' },
];

const formRules = {
  title: [{ required: true, message: '请输入模板标题' }],
  templateCode: [{ required: true, message: '请选择业务场景' }],
  templateId: [{ required: true, message: '请输入模板ID' }],
  status: [{ required: true, message: '请选择状态' }],
  remark: [{ required: true, message: '请填写备注' }],
};

// --- 表格操作 ---
const editKeyword = (record: Keyword) => {
  if (!editableKeywords[record.keywordId]) {
    editableKeywords[record.keywordId] = cloneDeep(record);
  }
};

const saveKeyword = (record: Keyword) => {
  const key = record.keywordId;
  const target = formData.value.keywordsList!.find(
    (item: Keyword) => item.keywordId === key,
  )!;
  Object.assign(target, editableKeywords[key]);
  delete editableKeywords[key];
  message.success('关键词已保存');
};

const cancelKeyword = (record: Keyword) => {
  const key = record.keywordId;
  delete editableKeywords[key];
};

// --- 抽屉逻辑 ---
const { onBeforeClose, markInitialized, resetInitialized } = useBeforeCloseDiff(
  {
    initializedGetter: () => JSON.stringify(formData.value),
    currentGetter: () => JSON.stringify(formData.value),
  },
);

const [BasicDrawer, drawerApi] = useVbenDrawer({
  class: 'w-[1000px]',
  onBeforeClose,
  onClosed: handleClosed,
  onConfirm: handleConfirm,
  onOpenChange: async (isOpen) => {
    if (!isOpen) return;
    drawerApi.drawerLoading(true);
    const { id } = drawerApi.getData() as { id?: string };
    isUpdate.value = !!id;
    if (id) {
      const record = await wxMsgTempInfo(id);
      formData.value = record;
    }
    await markInitialized();
    drawerApi.drawerLoading(false);
  },
});

async function handleConfirm() {
  if (Object.keys(editableKeywords).length > 0) {
    message.warning('您有正在编辑的关键词尚未保存');
    return;
  }
  try {
    await formRef.value.validate();
    drawerApi.lock(true);
    await (isUpdate.value
      ? wxMsgTempUpdate(formData.value as WxMsgTempForm)
      : wxMsgTempAdd(formData.value as WxMsgTempForm));
    resetInitialized();
    emit('reload');
    drawerApi.close();
  } catch (error) {
    console.error(error);
  } finally {
    drawerApi.lock(false);
  }
}

function handleClosed() {
  formRef.value.resetFields();
  formData.value = getDefaultValues();
  Object.keys(editableKeywords).forEach((key) => delete editableKeywords[key]);
  resetInitialized();
}
</script>

<template>
  <BasicDrawer :title="title">
    <Form
      ref="formRef"
      :model="formData"
      :rules="formRules"
      :label-col="{ span: 4 }"
      :wrapper-col="{ span: 20 }"
    >
      <FormItem label="模板标题" name="title">
        <Input v-model:value="formData.title" placeholder="请输入模板标题" />
      </FormItem>
      <FormItem label="业务场景" name="templateCode">
        <Select
          v-model:value="formData.templateCode"
          :options="planContentOptions"
          placeholder="请选择业务场景"
        />
      </FormItem>
      <FormItem label="模板ID" name="templateId">
        <Input
          v-model:value="formData.templateId"
          placeholder="请输入微信公众平台后台的模板ID"
        />
      </FormItem>
      <FormItem label="状态" name="status">
        <Select
          v-model:value="formData.status"
          :options="[
            { label: '启用', value: '0' },
            { label: '禁用', value: '1' },
          ]"
        />
      </FormItem>
      <FormItem label="跳转页面" name="pagePath">
        <Input
          v-model:value="formData.pagePath"
          placeholder="请输入小程序跳转页面路径"
        />
      </FormItem>
      <FormItem label="备注" name="remark">
        <Input.TextArea v-model:value="formData.remark" />
      </FormItem>

      <FormItem label="关键词配置">
        <Table
          :columns="keywordColumns"
          :data-source="formData.keywordsList"
          :pagination="false"
          bordered
          row-key="keywordId"
          size="small"
        >
          <template #bodyCell="{ column, record }">
            <template v-if="column.dataIndex === 'mappingField'">
              <div v-if="editableKeywords[record.keywordId]">
                <Input
                  v-model:value="
                    editableKeywords[record.keywordId]!.mappingField
                  "
                  placeholder="请输入映射字段"
                />
              </div>
              <div v-else>
                <Tag v-if="record.mappingField" color="blue">{{
                  record.mappingField
                }}</Tag>
                <span v-else class="text-gray-400">未映射</span>
              </div>
            </template>

            <template v-else-if="column.dataIndex === 'defaultValue'">
              <div v-if="editableKeywords[record.keywordId]">
                <Input
                  v-model:value="
                    editableKeywords[record.keywordId]!.defaultValue
                  "
                  placeholder="请输入默认值"
                />
              </div>
              <div v-else>
                {{ record.defaultValue || '-' }}
              </div>
            </template>

            <template v-else-if="column.dataIndex === 'operation'">
              <div class="editable-row-operations">
                <span v-if="editableKeywords[record.keywordId]">
                  <Button
                    type="link"
                    @click="saveKeyword(record as Keyword)"
                    style="padding-left: 0"
                    >保存</Button
                  >
                  <Popconfirm
                    title="确定取消吗?"
                    @confirm="cancelKeyword(record as Keyword)"
                  >
                    <Button type="link">取消</Button>
                  </Popconfirm>
                </span>
                <span v-else>
                  <Button
                    type="link"
                    @click="editKeyword(record as Keyword)"
                    style="padding-left: 0"
                    >编辑</Button
                  >
                </span>
              </div>
            </template>
          </template>
        </Table>
      </FormItem>
    </Form>
  </BasicDrawer>
</template>
